package com.itany.shop.service.impl;

import com.itany.shop.dao.ItemDao;
import com.itany.shop.dao.OrderDao;
import com.itany.shop.entity.Item;
import com.itany.shop.entity.Order;
import com.itany.shop.entity.User;
import com.itany.shop.exception.RequestParameterErrorException;
import com.itany.shop.exception.UserNotLoginException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.OrderService;
import com.itany.shop.util.ParameterUtil;
import com.itany.shop.vo.Cart;

import java.util.List;

public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = (OrderDao) ObjectFactory.getObject("orderDao");
    private ItemDao itemDao = (ItemDao) ObjectFactory.getObject("itemDao");

    @Override
    public String createOrder(Cart cart, User user) throws UserNotLoginException {
        if (cart == null || user == null) {
            throw new UserNotLoginException("登录失效,请先登录");
        }

        // 此时需要保存订单与该订单名下的明细信息
        // 保存明细的时候必须知道当前订单的编号
        // 因此,必须先保存订单,再保存明细

        // 1.保存订单
        Order order = new Order();
        order.setPrice(cart.getPrice());
        order.setUser(user);
        order.setNo(ParameterUtil.createNo());
        // 保存订单并返回主键
        Integer id = orderDao.insertReturnPrimaryKey(order);
        order.setId(id);

        // 2.保存明细
        // 取出购物车中每一条明细进行保存
        List<Item> items = cart.getItems();
        for (Item item : items) {
            // 将生成的订单赋值给当前明细,表示该明细属于指定订单
            item.setOrder(order);
            itemDao.insertItem(item);
        }
        return order.getNo();
    }

    @Override
    public List<Order> findMyOrders(User user) throws UserNotLoginException {
        if (user == null) {
            throw new UserNotLoginException("登录失效,请先登录!");
        }
        List<Order> orders = orderDao.selectByUserId(user.getId());
        return orders;
    }

    @Override
    public Order findOrderDetail(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Order order = orderDao.selectDetailById(Integer.parseInt(id));
        return order;
    }
}
